﻿using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace ExcelUnity.Importer.Wrappers.SheetDataBuilders
{
    public class DataTableBuilder
    {
        public static DataTable CreateDataTable(List<RowWrapper>? rows, List<ColumnWrapper>? columns)
        {
            if (rows == null || columns == null)
                return new DataTable();

            var dt = new DataTable();
            columns.ForEach(x => dt.Columns.Add(x.ColumnName));

            var columnPropertyDic = columns.ToDictionary(m => m.ColumnIndex);
            foreach (var row in rows)
            {
                DataRow dataRow = dt.NewRow();
                var index = 0;
                foreach (var cellWrapper in row.Cells.OrderBy(x => x.ColumnIndex))
                {
                    if (columnPropertyDic.TryGetValue(cellWrapper.ColumnIndex, out ColumnWrapper columnProperty))
                        dataRow[index++] = cellWrapper.Value;
                }
                dt.Rows.Add(dataRow);
                row.ModelData = dataRow;
            }

            return dt;
        }
    }
}
